/*
 * @Description: 按键c文件
 * @Author: TzzzT
 * @Date: 2022-04-05 19:05:41
 * @LastEditTime: 2023-02-05 18:13:36
 * @LastEditors: TzzzT
 */
#include "iot_button.h"
#include "esp_log.h"
#include "string.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "RCS_master.h"
#include "RCS_btn.h"
#include "RCS_ble_master.h"

static const char *TAG = "RCS_BTN";

extern rcs_mast_system_t rcsSystem;
extern TaskHandle_t bleserverTaskHandle;

static void button_single_click_cb(void *arg, void *data)
{
    ESP_LOGI(TAG, "BUTTON_SINGLE_CLICK");
    // 通知所有从机
    uint16_t packlen;
    uint8_t *sync_ble_server_data = make_sync_data_package(&packlen, 1 << POWER_OFF_NOTIFY);
    if (rcsSystem.equip.pri_weapon.point.is_hold)
    {
        rcs_send_to_bleserver(GUN_POINT_CLASS, sync_ble_server_data, packlen);
    }
    if (rcsSystem.equip.pri_weapon.screen.is_hold)
    {
        rcs_send_to_bleserver(GUN_SCREEN_CLASS, sync_ble_server_data, packlen);
    }
    if (rcsSystem.equip.armor.is_hold)
    {
        rcs_send_to_bleserver(ARMOR_CLASS, sync_ble_server_data, packlen);
    }
    free(sync_ble_server_data);
    power_off();
}

static void button_long_click_cb(void *arg, void *data)
{
    ESP_LOGI(TAG, "BUTTON_LONG_CLICK");
    set_allow_scan_new_slave_flag(true);
}

/**
 * @description: 按键初始化
 * @param  {void}
 * @return {void}
 * @Author: TzzzT
 * @Date: 2022-04-19 23:51:14
 * @LastEditTime: Do not edit
 * @LastEditors: Shadow
 */
 

void btn_init(void)
{
    // create gpio button
    button_config_t gpio_btn_cfg = {
        .type = BUTTON_TYPE_GPIO,
        .long_press_time = 1500,
        .short_press_time = 180,
        .gpio_button_config = {
            .gpio_num = BTN_GPIO_NUM,
            .active_level = 0,
        },
    };
    button_handle_t gpio_btn = iot_button_create(&gpio_btn_cfg);
    if (NULL == gpio_btn)
    {
        ESP_LOGE(TAG, "Button create failed");
    }
    ESP_LOGE(TAG, "Button create!");
    iot_button_register_cb(gpio_btn, BUTTON_SINGLE_CLICK, button_single_click_cb, NULL);
    iot_button_register_cb(gpio_btn, BUTTON_LONG_PRESS_START, button_long_click_cb, NULL);
}

